import ButtonGroup, { Button } from "@/components/ButtonGroup";
import ScrollList from "@/components/ScrollList";
import { useMemo, useState } from "react";
import { View } from "@tarojs/components";
import Cell from "@/components/Cell";
import styles from "./style.scss";
import Checkbox from "../Checkbox";
import { showToast } from "@tarojs/taro";

type Props<T> = {
  onConfirm: (data: any) => void;
  loading: boolean;
  onCancel?: () => void;
  data?: T[];
  name?: string;
  replaceKey?: {
    name: string;
    value: string;
  };
  multiple?: boolean;
  tip?: string;
  buttonRender: () => React.ReactNode;
};
export default <T = any,>(props: Props<T>) => {
  const {
    data,
    loading,
    multiple,
    replaceKey = { name: "name", value: "id" },
    onConfirm,
    buttonRender,
    tip,
  } = props;
  const [visible, setVisible] = useState(false);
  const [selectItems, setSelectItems] = useState<T[]>([]);

  const ids = useMemo(
    () => selectItems.map((item) => item[replaceKey.value]),
    [selectItems, replaceKey]
  );

  const onCheck = (checked: boolean, item) => {
    const filter = selectItems.filter(
      (orgin) => orgin[replaceKey.value] !== item[replaceKey.value]
    );
    if (checked) {
      if (multiple) {
        filter.push(item);
      } else {
        setSelectItems([item]);
        return;
      }
    }
    setSelectItems([...filter]);
  };

  return (
    <View className={styles.container}>
      <View
        onClick={() => {
          setVisible(true);
        }}
      >
        {buttonRender()}
      </View>
      <View
        className={styles.selectPanel}
        style={{ display: visible ? "flex" : "none" }}
      >
        {tip && (
          <View className={styles.header}>
            <View className={styles.tip}>{tip}</View>
          </View>
        )}
        <View className={styles.listWrap}>
          <ScrollList
            data={data}
            loading={loading}
            renderItem={(item) => (
              <Cell
                title={item?.[replaceKey?.name]}
                key={item?.[replaceKey?.value]}
                className={styles.cell}
                right={
                  <Checkbox
                    checked={ids.includes(item[replaceKey.value])}
                    onChange={(e) => onCheck(e, item)}
                  />
                }
              />
            )}
          />
        </View>
        <ButtonGroup>
          <Button onClick={() => setVisible(false)}>取消</Button>
          <Button
            type="primary"
            onClick={() => {
              if (selectItems.length === 0) {
                showToast({
                  title: "请选择",
                  icon: "none",
                });
                return;
              }
              onConfirm(selectItems);
              setVisible(false);
            }}
          >
            确定
          </Button>
        </ButtonGroup>
      </View>
    </View>
  );
};
